/**
 * 
 */
package com.ideeli.webextractor.service;

import static com.ideeli.webextractor.utils.Constants.*;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.ideeli.webextractor.dao.ProductDao;
import com.ideeli.webextractor.utils.Utility;

/**
 * @author sa
 * 
 */
public class SISParserImpl implements SISParser
{

	private static final Logger logger = Logger.getLogger(SISParserImpl.class);
	
	
	private ProductService productService;
	private ProductDao productDao;
	private CacheService cacheService;
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ideeli.webextractor.service.SISParser#readXls(java.lang.String)
	 */
	@Override
	public void process(String fileName) 
	{
		try {
			
			processXls(fileName);
			productService.deleteUnlisted(SIS_ID);
			
		} catch (Exception e) 
		{
			logger.error("Exception in process:",e);
		} 
		
		
		
		Map<String,String> updatedPriceList=cacheService.getUpdateProdPriceList();
		
		for(String productId: updatedPriceList.keySet())
		{
			logger.warn("productId:"+productId+"  "+updatedPriceList.get(productId) );
		}
		
//		productImageService.synchronizeImages();
		
		logger.info("\n\n\n");
		List<String> errorList=cacheService.getErrorList();
		
		for(String str: errorList)
		{
			logger.warn(str);
		}
		
		logger.warn("All done!!\n\n\n");
	}

	public void processXls(String fileName) throws Exception
	{
		logger.warn("Start readXls");

		Workbook workbook = WorkbookFactory.create(new File(fileName));
		// Sheet sheet = workbook.getSheet("Adobe Retail");

//		parseRows(workbook,APL,250,25,4);
		parseRows(workbook,WD,100,15,4);
		parseRows(workbook,HTC,100,15,4);
//		parseRows(workbook,SAM_TAB_MOB,20,15,2);
	

		logger.warn("\n\nFinish readXls\n\n");
	}

	public void parseRows(Workbook workbook,String brand, int rows, int cols, int stRow) throws Exception
	{
		logger.warn("Start parseRows "+brand);
		
		Sheet sheet = workbook.getSheet(brand);
		Iterator<Row> rowIter = sheet.iterator();
		int r = 0;
		while (rowIter.hasNext())
		{
			Row row = rowIter.next();
			r++;
			if (r > rows)
				break;// around 200 filled product rows only for apple

			int c = 0;
			Iterator<Cell> cellIter = row.cellIterator();
			StringBuilder cellBuilder = new StringBuilder(r+"|");
			while (cellIter.hasNext())
			{
				if (c > cols)
					break;//around 25 columns for apple

				c++;
				Cell cell = cellIter.next();
				cellBuilder.append(cell);
				cellBuilder.append("|");

			}
			logger.info("row=" + r + " " + "cell=" + cellBuilder);
			 
			{
				if (r > stRow)
				{
					if(WD.equals(brand))
					{
						mapWD(cellBuilder.toString());	
					}
					else if(APL.equals(brand))
					{
						mapApl(cellBuilder.toString());
					}
					else if(HTC.equals(brand))
					{
						mapHTC(cellBuilder.toString());
					}
					else if(SAM_TAB_MOB.equals(brand))
					{
//						mapSamTabMob(cellBuilder.toString());
					}
						
				}
			}
		}
		
	}
	
	/**
	 * 
	 * 2|Samsung|Mobile |Tablet|1004 8710|SAMSUNG GALAXY TAB 2 10.1 P5100 16GB (NEW)
SILVER P5100TSAXSP|http://www.gsmarena.com/samsung_galaxy_tab_2_10_1_p5100-4567.php |665.0|798.0|H2/1.07|3 - 5 working days| 
	 * 
	 * @param row
	 * @throws Exception
	 */
	private void mapSamTabMob(String row) throws Exception 
	{
		
		String cells[]=row.split("\\|");
		
		//Apple product starts from 2nd column Apple String
		if(cells!=null && cells.length> 3 && APL.equals(cells[2]))
		{
			String brand=APL;
			String model=cells[3];
			String sku=brand+cells[0];
			
			String upc=cells[7];
			if(Utility.isNull(upc))
				upc=model;
			
			
			String basePrice=cells[10];
			
			String stnRetailPrice=cells[8];
			
			
			
			String name=APL+" "+cells[5].trim()+ " "+cells[4].trim();
			String meta=name;
			String prodDesc=cells[4].trim();
			String subCat=cells[5].trim();
			
			String image="data/images/large/"+subCat+".jpg";
			String topCat=brand;
			productService.insertSISProduct(model,sku,upc,brand,basePrice,stnRetailPrice,image,name,meta,SIS,prodDesc,subCat,topCat);
		
		}
	}

	/*      0   1     2        3         4              5       6       7    8      9    10     11
	 * cell=4|Mobile|HTC|99HRL059-00|HTC One X (White)|Mobile|868.0|F4/1.07|600.0|G4-H4|I4/G4|Special Clearance| 
	 */
	private void mapHTC(String row) throws Exception{
		
		String cells[]=row.split("\\|");
		
		//Apple product starts from 2nd column Apple String
		if(cells!=null && cells.length> 2 && HTC.equals(cells[2]))
		{
			String brand=HTC;
			String model=cells[3];
			String sku=brand+cells[0];
			
			String upc=model;
			
			String basePrice=cells[8];
			
			String stnRetailPrice=cells[6];
			
			
			
			String name=cells[4].trim()+ " "+cells[3].trim();
			String meta=name;
			String prodDesc=name + " "+cells[5].trim();
			String subCat=brand;
			
			String image="data/images/large/"+subCat+".jpg";
			String topCat="Mobile";
			productService.insertSISProduct(model,sku,upc,brand,basePrice,stnRetailPrice,image,name,meta,SIS,prodDesc,subCat,topCat);
		}
		
		
	}

	private void mapWD(String row) throws Exception
	{
		//r0         upc 1          part 2          name 3                               chp 4             ret5
		//5|7.18037770567E11|WDBACW0010HBK-SESN|WD My Book Essential USB3.0 1TB (3.5")|128.11214953271028|149.0|| 
		String cells[]=row.split("\\|");
		
		//Apple product starts from 2nd column Apple String
		if(cells!=null && cells.length> 2 && cells[2].startsWith("WD"))
		{
			String brand=WD;
			String model=cells[2];
			String sku=brand+cells[0];
			
			String upc=cells[1];
			if(Utility.isNull(upc))
				upc=model;
			
			
			String basePrice=cells[4];
			
			String stnRetailPrice=cells[5];
			
			
			
			String name=brand+" "+cells[3].trim()+ " "+cells[2].trim();
			String meta=name;
			String prodDesc=name;
			String subCat=brand;
			
			String image="data/images/large/"+subCat+".jpg";
			String topCat="Storage";
			productService.insertSISProduct(model,sku,upc,brand,basePrice,stnRetailPrice,image,name,meta,SIS,prodDesc,subCat,topCat);
			
		}

	}
	


	private void mapApl(String row) throws Exception
	{
		
		String cells[]=row.split("\\|");
		
		//Apple product starts from 2nd column Apple String
		if(cells!=null && cells.length> 3 && APL.equals(cells[2]))
		{
			String brand=APL;
			String model=cells[3];
			String sku=brand+cells[0];
			
			String upc=cells[7];
			if(Utility.isNull(upc))
				upc=model;
			
			
			String basePrice=cells[10];
			
			String stnRetailPrice=cells[8];
			
			
			
			String name=APL+" "+cells[5].trim()+ " "+cells[4].trim();
			String meta=name;
			String prodDesc=cells[4].trim();
			String subCat=cells[5].trim();
			
			String image="data/images/large/"+subCat+".jpg";
			String topCat=brand;
			productService.insertSISProduct(model,sku,upc,brand,basePrice,stnRetailPrice,image,name,meta,SIS,prodDesc,subCat,topCat);
			
		}

	}
	
/*
	public void parseApple(Sheet sheet) throws Exception
	{
		logger.warn("Start parseApple");
		Iterator<Row> rowIter = sheet.iterator();
		int r = 0;
		while (rowIter.hasNext())
		{
			Row row = rowIter.next();
			r++;
			if (r > 250)
				break;// around 200 filled product rows only for apple

			int c = 0;
			Iterator<Cell> cellIter = row.cellIterator();
			StringBuilder cellBuilder = new StringBuilder(r+"|");
			while (cellIter.hasNext())
			{
				if (c > 25)
					break;//around 25 columns for apple

				c++;
				Cell cell = cellIter.next();
				cellBuilder.append(cell);
				cellBuilder.append("|");

			}
			logger.info("row=" + r + " " + "cell=" + cellBuilder);

			// from 4th row product starts
			if (r > 4)
			{
				mapApple(cellBuilder.toString());
			}

		}

	}*/
	


	public ProductService getProductService()
	{
		return productService;
	}

	public void setProductService(ProductService productService)
	{
		this.productService = productService;
	}

	public ProductDao getProductDao()
	{
		return productDao;
	}

	public void setProductDao(ProductDao productDao)
	{
		this.productDao = productDao;
	}

	public CacheService getCacheService() {
		return cacheService;
	}

	public void setCacheService(CacheService cacheService) {
		this.cacheService = cacheService;
	}

}
